/**
 * Copyright (c) 2006 RiseSoft Co.,Ltd  
 * $Header$
 */
package net.risesoft.risebi.collection.web;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.risesoft.risebi.collection.model.Application;
import net.risesoft.risebi.collection.model.Bulletin;
import net.risesoft.risebi.collection.model.BulletinAttachment;
import net.risesoft.risebi.collection.model.BulletinReceiver;
import net.risesoft.risebi.collection.model.ComboDefine;
import net.risesoft.risebi.collection.model.NotificationReceiver;
import net.risesoft.risebi.collection.model.Service;
import net.risesoft.risebi.collection.model.User;
import net.risesoft.risebi.collection.service.ApplicationManager;
import net.risesoft.risebi.collection.service.BulletinAttachmentManager;
import net.risesoft.risebi.collection.service.BulletinManager;
import net.risesoft.risebi.collection.service.BulletinReceiverManager;
import net.risesoft.risebi.collection.service.ComboDefineManager;
import net.risesoft.risebi.collection.service.ServiceManager;
import net.risesoft.risebi.collection.service.UserManager;
import net.risesoft.risebi.collection.web.BaseAction;
import net.risesoft.risebi.commons.util.GUID;
import net.risesoft.risebi.commons.util.JSONUtil;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.LazyDynaBean;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

/**
 * NotificationAction
 *
 * @author <a href="mailto: dingzhaojun@risesoft.net">丁兆俊</a>
 * @version $Revision$
 * 
A custom Result type for sending raw data (via an InputStream) directly to the HttpServletResponse. Very useful for allowing users to download content.
    * contentType - the stream mime-type as sent to the web browser (default = text/plain).
    * contentLength - the stream length in bytes (the browser displays a progress bar).
    * contentDisposition - the content disposition header value for specifing the file name (default = inline, values are typically attachment;filename="document.pdf".
    * inputName - the name of the InputStream property from the chained action (default = inputStream).
    * bufferSize - the size of the buffer to copy from input to output (default = 1024).
    * allowCaching if set to 'false' it will set the headers 'Pragma' and 'Cache-Control' to 'no-cahce', and prevent client from caching the content. (default = true)
    * contentCharSet if set to a string, ';charset=value' will be added to the content-type header, where value is the string set. If set to an expression, the result of evaluating the expression will be used. If not set, then no charset will be set on the header

These parameters can also be set by exposing a similarly named getter method on your Action. For example, you can provide getContentType() to override that parameter for the current action.
Examples

<result name="success" type="stream">
  <param name="contentType">image/jpeg</param>
  <param name="inputName">imageStream</param>
  <param name="contentDisposition">attachment;filename="document.pdf"</param>
  <param name="bufferSize">1024</param>
</result>
 * 
 */

public class BaseBulletinAction extends BaseAction{
	private static final long serialVersionUID = -5348665261143362121L;
	private static Log log = LogFactory.getLog(BaseBulletinAction.class);
	
	private ServiceManager serviceManager;
	private ApplicationManager applicationManager;
	private BulletinManager bulletinManager;
	private BulletinAttachmentManager bulletinAttachmentManager;
	private BulletinReceiverManager bulletinReceiverManager;
	private UserManager userManager;
	private ComboDefineManager comboDefineManager;

	private Bulletin bulletin;

	//以下三个字段用于文件上载
	private File attachment;
	private String attachmentFileName;
	private String attachmentContentType;
	
	//以下七个字段用于文件下载
	private InputStream fileStream;
	private String contentType;
	private String contentDisposition;
	private String contentCharSet;
	private int bufferSize = 4096;
	private int contentLength;
	private boolean allowCaching = false;	

	@SuppressWarnings("unchecked")
	@Action(value="refreshJson")
	public String refreshJson() throws Exception {
		try{
			if("jsonList".equalsIgnoreCase(this.whichJson)){
				if(this.bulletin==null){
					this.bulletin = new Bulletin();
				}
				Map mapBulletins = bulletinManager.getPagedByBulletin(bulletin, this.start, this.limit);
				List<Bulletin> list = (List<Bulletin>)mapBulletins.get("list");
				
				/*Map map = new HashMap();
				int count = bulletinManager.getCount("select count(*) from Bulletin");
				List<Bulletin> list = bulletinManager.find("from Bulletin n order by n.publishTime desc", this.start, this.limit);	
				
				User user = this.getSessionUser();
				if(user.getUserType()==User.USERTYPE_ENTERPRISEUSER){
					count = bulletinManager.getCount("select count(*) from Bulletin n where n.auditStatus=true and n.guid in (select t.bulletin.guid from BulletinReceiver t where t.applicationGuid in (select s.so.application.guid from UserSO s where s.user.guid='" + user.getGuid() + "'))");
					list = bulletinManager.find("from Bulletin n where n.auditStatus=true and n.guid in (select t.bulletin.guid from BulletinReceiver t where t.applicationGuid in (select s.so.application.guid from UserSO s where s.user.guid='" + user.getGuid() + "')) order by n.topStatus desc,n.publishTime desc", this.start, this.limit);	
				}*/
				
				List newList = new ArrayList();
				for(Bulletin n : list){
					Map m = new HashMap();					
					m.put("guid", n.getGuid());
					m.put("title", n.getTitle());
					m.put("type", n.getType());
					m.put("publishTime", DateFormatUtils.format(n.getPublishTime(),"yyyy-MM-dd"));
					m.put("auditStatus", n.getAuditStatus());
					m.put("topStatus", n.getTopStatus());
					m.put("content", n.getContent());
					m.put("tabIndex", n.getTabIndex());
					
					int attachments = bulletinAttachmentManager.getCount("select count(*) from BulletinAttachment t where t.bulletin.guid='" + n.getGuid() + "'");
					m.put("attachments", attachments);
					
					newList.add(m);
				}
				
				//mapBulletins.put("count", count);
				mapBulletins.put("list", newList);
				this.json = JSONUtil.getJsonString(null,null,mapBulletins);
			}else if("jsonAttachments".equalsIgnoreCase(this.whichJson)){
				List<BulletinAttachment> list = bulletinAttachmentManager.find("from BulletinAttachment t where t.bulletin.guid='" + bulletin.getGuid() + "' order by tabIndex asc");
				List newList = new ArrayList();
				for(BulletinAttachment na : list){
					Map m = new HashMap();	
					m.put("guid", na.getGuid());
					m.put("href", this.getContextPath() + "/client/BulletinAction/download.action?node=" + na.getGuid());
					m.put("name", na.getName());
					m.put("extension", na.getExtension());
					m.put("size", na.getSize());
					m.put("tabIndex", na.getTabIndex());
					newList.add(m);
				}
				this.json = JSONUtil.getJsonString(null,null,newList);
			}else if("jsonReceivers".equalsIgnoreCase(this.whichJson)){
				List<BulletinReceiver> list = bulletinReceiverManager.find("from BulletinReceiver t where t.bulletin.guid='"+ bulletin.getGuid() + "' order by t.serviceGuid,t.applicationGuid");
				List newList = new ArrayList();
				for(BulletinReceiver r : list){
					Map m = new HashMap();
					m.put("guid", r.getGuid());
					m.put("serviceGuid", r.getServiceGuid());
					m.put("applicationGuid", r.getApplicationGuid());
					
					Service service = (Service)serviceManager.getObject(Service.class, r.getServiceGuid());
					m.put("serviceName", service.getName());
					
					Application app = (Application)applicationManager.getObject(Application.class, r.getApplicationGuid());
					m.put("applicationName", app.getChineseName());				
					
					newList.add(m);
				}		
				this.json = JSONUtil.getJsonString(null,null,newList);
			}else if("jsonApplications".equalsIgnoreCase(this.whichJson)){
				Service service = (Service)serviceManager.getObject(Service.class, this.node);
				List<Application> list = service.getApplications();
				List newList = new ArrayList();
				for(Application a : list){
					Map m = new HashMap();
					m.put("guid", a.getGuid());
					m.put("name", a.getChineseName());					
					newList.add(m);
				}		
				this.json = JSONUtil.getJsonString(null,null,newList);
			}else if("jsonBulletinTypes".equalsIgnoreCase(this.whichJson)){
				ArrayList newlist = new ArrayList();
				List<ComboDefine> list = comboDefineManager.getAllItemsByType("公告类别");
				if(list.size()==0){
					ComboDefine c = new ComboDefine();
					c.setGuid(new GUID().toString(32));
					c.setType("公告类别");
					c.setCode("普通公告");
					c.setName("普通公告");
					c.setTabIndex(1d);
					comboDefineManager.saveObject(c);
					
					Map map = new HashMap();
					map.put("guid", "普通公告");
					map.put("name", "普通公告");
					newlist.add(map);
				}else{
					for(ComboDefine c : list){
						Map map = new HashMap();
						map.put("guid", c.getName());
						map.put("name", c.getName());
						newlist.add(map);
					}
				}		
				this.json = JSONUtil.getJsonString(null, null, newlist);
			}
		}catch(Exception e){
			this.json = "[]";
			//e.printStackTrace();
		} 

		return AJAX;
	}
	
	@Action(value="list",
			results={@Result(name="success", location="/client/bulletin/bulletinList.jsp")}
	)
	public String list() throws Exception {
		return SUCCESS;
	}	

	@Action(value="prepareEdit",
			results={@Result(name="success", location="/client/bulletin/bulletinEdit.jsp")}
	)
	public String prepareEdit() throws Exception {
		String guid = bulletin.getGuid();
		if(guid==null || guid.trim().length()==0){
			bulletin = new Bulletin();
			bulletin.setGuid(new GUID().toString(32));			
		}else{
			bulletin = (Bulletin)bulletinManager.getObject(Bulletin.class, bulletin.getGuid());
		}
		
		if(bulletin.getTabIndex()==null){
			bulletin.setTabIndex(1d);
		}
		if(bulletin.getAuditStatus()==null){
			bulletin.setAuditStatus(false);
		}
		if(bulletin.getTopStatus()==null){
			bulletin.setTopStatus(false);
		}
		
		ArrayList newlist = new ArrayList();
		List<ComboDefine> list = comboDefineManager.getAllItemsByType("公告类别");
		if(list.size()==0){
			ComboDefine c = new ComboDefine();
			c.setGuid(new GUID().toString(32));
			c.setType("公告类别");
			c.setCode("普通公告");
			c.setName("普通公告");
			c.setTabIndex(1d);
			comboDefineManager.saveObject(c);
			
			Map map = new HashMap();
			map.put("guid", "普通公告");
			map.put("name", "普通公告");
			newlist.add(map);
		}else{
			for(ComboDefine c : list){
				Map map = new HashMap();
				map.put("guid", c.getName());
				map.put("name", c.getName());
				newlist.add(map);
			}
		}		
		this.json = JSONUtil.getJsonString(null, null, newlist);
		
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	@Action(value="prepareView",
			results={@Result(name="success", location="/client/bulletin/bulletinView.jsp")}
	)
	public String prepareView() throws Exception {
		bulletin = (Bulletin)bulletinManager.getObject(Bulletin.class, bulletin.getGuid());
		return SUCCESS;
	}
	
	@Action(value="prepareAddAttachments",
			results={@Result(name="success", location="/client/bulletin/addAttachments.jsp")}
	)
	public String prepareAddAttachments() throws Exception {
		return SUCCESS;
	}
	
	@Action(value="prepareAddApplications",
			results={@Result(name="success", location="/client/bulletin/addApplications.jsp")}
	)
	public String prepareAddApplications() throws Exception {
		ArrayList newList = new ArrayList();
		List<Service> list = serviceManager.getServicesWithPermission(this.getSessionUser());
		for(Service service : list){
			Map map = new  HashMap();	
			map.put("guid", service.getGuid());
			map.put("name", service.getName());
			newList.add(map);
		}		
		this.json = JSONUtil.getJsonString(null, null, newList);	
		
		return SUCCESS;
	}
	
	@Action(value="edit")
	public String edit() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			Bulletin note = (Bulletin)bulletinManager.getObject(Bulletin.class, bulletin.getGuid());
			if(note==null){
				bulletinManager.saveObject(bulletin);
			}else{
				note.setTitle(bulletin.getTitle());
				note.setType(bulletin.getType());
				note.setPublishTime(bulletin.getPublishTime());
				note.setAuditStatus(bulletin.getAuditStatus());
				note.setTopStatus(bulletin.getTopStatus());				
				note.setContent(bulletin.getContent());
				note.setTabIndex(bulletin.getTabIndex());
				bulletinManager.saveObject(note);
			}						

			ldb.set("success", true);
			ldb.set("reason", "保存成功！");
			
			ldb.set("guid", bulletin.getGuid());
			ldb.set("title", bulletin.getTitle());
			ldb.set("type", bulletin.getType());			
			ldb.set("publishTime", DateFormatUtils.format(bulletin.getPublishTime(),"yyyy-MM-dd"));			
			ldb.set("content", bulletin.getContent());
			ldb.set("auditStatus", bulletin.getAuditStatus());
			ldb.set("topStatus", bulletin.getTopStatus());
			ldb.set("tabIndex", bulletin.getTabIndex());

			int attachments = bulletinAttachmentManager.getCount("select count(*) from BulletinAttachment t where t.bulletin.guid='" + bulletin.getGuid() + "'");
			ldb.set("attachments", attachments);
			
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}
		
		return AJAX;
	}

	@Action(value="remove")
	public String remove() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			bulletinAttachmentManager.execute("delete from BulletinAttachment t where t.bulletin.guid='" + node + "'");
			bulletinReceiverManager.execute("delete from BulletinReceiver t where t.bulletin.guid='" + node + "'");
			bulletinManager.execute("delete from Bulletin t where t.guid='" + node + "'");			
			
			ldb.set("success", true);
			ldb.set("reason", "删除成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}

		return AJAX;
	}
	
	@Action(value="upload",
			results={@Result(name="ajax", type="ajax",params={"contentType","text/html"})}
	)
	public String upload() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			Bulletin note = (Bulletin)bulletinManager.getObject(Bulletin.class, bulletin.getGuid());
			if(note==null){
				bulletinManager.saveObject(bulletin);
			}

			BulletinAttachment a = new BulletinAttachment();
			a.setGuid(new GUID().toString(32));
			a.setExtension(FilenameUtils.getExtension(this.attachmentFileName));
			a.setName(this.attachmentFileName);
			a.setBulletin(bulletin);
			a.setSize(String.valueOf(this.attachment.length()));
			a.setTabIndex(1d);
			a.setContent(FileUtils.readFileToByteArray(this.attachment));
			bulletinAttachmentManager.saveObject(a);
			
			ldb.set("success", true);
			ldb.set("reason", "保存成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
		}
		
		return AJAX;
	}
	
	@Action(value="download",
			results={@Result(name="success", type="stream",params={"inputName","fileStream"})}
	)
	public String download() throws Exception {
		ByteArrayInputStream bais = null;
		
		try{
			BulletinAttachment a = (BulletinAttachment)bulletinAttachmentManager.getObject(BulletinAttachment.class, node);
			
			byte[] b = a.getContent();
			
			bais = new ByteArrayInputStream(b);
			this.fileStream = bais;
			this.contentLength = b.length;
			this.contentType = "application/octet-stream";
			this.contentDisposition = "attachment; filename=" + a.getName();
			
			return SUCCESS;
		}catch(Exception e){
			e.printStackTrace();
		}
				
		return SUCCESS;
	}
	
	@Action(value="removeAttachments")
	public String removeAttachments() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			if("all".equals(this.source)){
				bulletinAttachmentManager.execute("delete from BulletinAttachment t where t.bulletin.guid='" + bulletin.getGuid() + "'");
			}else{
				String[] ss = this.source.split(",");
				for(String s : ss){
					bulletinAttachmentManager.execute("delete from BulletinAttachment t where t.guid='" + s + "'");
				}
			}
			ldb.set("success", true);
			ldb.set("reason", "删除成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}

		return AJAX;
	}
	
	@SuppressWarnings("unchecked")
	@Action(value="addReceivers")
	public String addReceivers() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			Bulletin note = (Bulletin)bulletinManager.getObject(Bulletin.class, bulletin.getGuid());
			if(note==null){
				bulletinManager.saveObject(bulletin);
			}			
			
			String[] applicationGuids = this.source.split(",");
			for(String applicationGuid : applicationGuids){
				BulletinReceiver r = new BulletinReceiver();
				r.setGuid(new GUID().toString(32));
				
				List<BulletinReceiver> listReceivers = bulletinReceiverManager.find("from BulletinReceiver t where t.bulletin.guid='" + bulletin.getGuid() + "' and t.serviceGuid='" + this.node + "' and t.applicationGuid='" + applicationGuid + "'");
				if(listReceivers.size()>0){						
					r = listReceivers.get(0);
				}
				r.setBulletin(bulletin);
				r.setServiceGuid(this.node);
				r.setApplicationGuid(applicationGuid);
				
				bulletinReceiverManager.saveObject(r);
			}
			
			ldb.set("success", true);
			ldb.set("reason", "保存成功！");
			
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}
		
		return AJAX;
	}
	
	@Action(value="removeReceivers")
	public String removeReceivers() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			if("all".equals(this.source)){
				bulletinReceiverManager.execute("delete from BulletinReceiver t where t.bulletin.guid='" + bulletin.getGuid() + "'");
			}else{
				String[] ss = this.source.split(",");
				for(String s : ss){
					bulletinReceiverManager.execute("delete from BulletinReceiver t where t.guid='" + s + "'");
				}
			}
			ldb.set("success", true);
			ldb.set("reason", "删除成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}

		return AJAX;
	}

	public ServiceManager getServiceManager() {
		return serviceManager;
	}

	public void setServiceManager(ServiceManager serviceManager) {
		this.serviceManager = serviceManager;
	}

	public ApplicationManager getApplicationManager() {
		return applicationManager;
	}

	public void setApplicationManager(ApplicationManager applicationManager) {
		this.applicationManager = applicationManager;
	}

	public BulletinManager getBulletinManager() {
		return bulletinManager;
	}

	public void setBulletinManager(BulletinManager bulletinManager) {
		this.bulletinManager = bulletinManager;
	}

	public BulletinAttachmentManager getBulletinAttachmentManager() {
		return bulletinAttachmentManager;
	}

	public void setBulletinAttachmentManager(
			BulletinAttachmentManager bulletinAttachmentManager) {
		this.bulletinAttachmentManager = bulletinAttachmentManager;
	}

	public UserManager getUserManager() {
		return userManager;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	public Bulletin getBulletin() {
		return bulletin;
	}

	public void setBulletin(Bulletin bulletin) {
		this.bulletin = bulletin;
	}

	public File getAttachment() {
		return attachment;
	}

	public void setAttachment(File attachment) {
		this.attachment = attachment;
	}

	public String getAttachmentFileName() {
		return attachmentFileName;
	}

	public void setAttachmentFileName(String attachmentFileName) {
		this.attachmentFileName = attachmentFileName;
	}

	public String getAttachmentContentType() {
		return attachmentContentType;
	}

	public void setAttachmentContentType(String attachmentContentType) {
		this.attachmentContentType = attachmentContentType;
	}

	public InputStream getFileStream() {
		return fileStream;
	}

	public void setFileStream(InputStream fileStream) {
		this.fileStream = fileStream;
	}

	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public String getContentDisposition() {
		return contentDisposition;
	}

	public void setContentDisposition(String contentDisposition) {
		this.contentDisposition = contentDisposition;
	}

	public String getContentCharSet() {
		return contentCharSet;
	}

	public void setContentCharSet(String contentCharSet) {
		this.contentCharSet = contentCharSet;
	}

	public int getBufferSize() {
		return bufferSize;
	}

	public void setBufferSize(int bufferSize) {
		this.bufferSize = bufferSize;
	}

	public int getContentLength() {
		return contentLength;
	}

	public void setContentLength(int contentLength) {
		this.contentLength = contentLength;
	}

	public boolean isAllowCaching() {
		return allowCaching;
	}

	public void setAllowCaching(boolean allowCaching) {
		this.allowCaching = allowCaching;
	}

	public BulletinReceiverManager getBulletinReceiverManager() {
		return bulletinReceiverManager;
	}

	public void setBulletinReceiverManager(
			BulletinReceiverManager bulletinReceiverManager) {
		this.bulletinReceiverManager = bulletinReceiverManager;
	}

	public ComboDefineManager getComboDefineManager() {
		return comboDefineManager;
	}

	public void setComboDefineManager(ComboDefineManager comboDefineManager) {
		this.comboDefineManager = comboDefineManager;
	}

}
